import { useEffect, useState } from "react";
import api from "../../request";
import AdminBaseTable from "../../Component/AdminBaseTable";
import { Author } from "poetry";
import { Container } from "react-bootstrap";
import useMessageBox from "../../Modal/MessageBox_Context";
import { useNavigate, useSearchParams } from "react-router-dom";
import useEditBox from "../../Modal/EditBox_Content";
import { Button } from "react-bootstrap";
import { useRequireLogin } from "../../utils";

function AdminAuthorsPage() {
    useRequireLogin(true);

    let [searchParams, setSearchParams] = useSearchParams();
    const navigate = useNavigate();
    /** @typedef {[Author, ]} */
    const [authors, setAuthors] = useState([]);
    const [currentPage, setCurrentPage] = useState(0);
    const [totalPages, setTotalPages] = useState(0);

    const showMessageBox = useMessageBox();
    const showEditBox = useEditBox();

    const editBoxArgs = {
        schema: {
            name: {
                label: '作者',
                type: 'text',
            },
            dynasty: {
                label: '朝代',
                type: 'text',
            },
            desc: {
                label: '描述',
                type: 'textarea',
            },
        },
        options: {
            title: '编辑作者',
            withCancel: true,
            withSubmit: true,
            withClose: true,
            onSubmit: (formData, onClose) => {
                console.log('EditAuthor', formData);
                api.updateAuthor(formData, (err, data, _) => {
                    if (err) throw err;
                    console.log(data);
                    onClose();
                    if (data.code === 403)
                        showMessageBox('编辑失败', '权限不足。', 'ok');
                    else if (data.code !== 0)
                        showMessageBox('编辑失败', data.msg, 'ok');
                    else {
                        showMessageBox('编辑成功', '编辑成功！', 'ok').then(fetchData);
                    }
                });
            }
        },
    }
    const addBoxArgs = Object.assign({}, editBoxArgs, {
        options: {
            title: '添加作者',
            withCancel: true,
            withSubmit: true,
            withClose: true,
            onSubmit: (formData, onClose) => {
                console.log('AddAuthor', formData);
                api.addAuthor(formData, (err, data, _) => {
                    if (err) throw err;
                    console.log(data);
                    onClose();
                    if (data.code === 403)
                        showMessageBox('添加失败', '权限不足。', 'ok');
                    else if (data.code !== 0)
                        showMessageBox('添加失败', data.msg, 'ok');
                    else {
                        showMessageBox('添加成功', '添加成功！', 'ok').then(fetchData);
                    }
                });
            }
        }
    });

    function fetchData() {
        let page = searchParams.get('page') ? parseInt(searchParams.get('page')) : 0
        api.listAuthors({
            page: page,
            size: 20
        }, (err, data, _) => {
            if (err) throw err;
            setAuthors(data.data.list);
            setTotalPages(data.data.totalPage);
            setCurrentPage(page);
        });
    }

    useEffect(fetchData, [searchParams]);

    function gotoPage(page) {
        // navigate(`/poem?page=${page}`)
        setSearchParams({ page: page });
        // setCurrentPage(page);
        window.scrollTo(0, 0);
        
    }


    return (
        <Container>
            <h1>作者管理</h1>
            <Button variant="primary" className="mb-3 mt-3" onClick={() => {
                showEditBox(addBoxArgs.schema, addBoxArgs.options);
            }}>添加</Button>
            <AdminBaseTable className="" data={{
                columns: {
                    name: '名称',
                    dynasty: '朝代',
                    desc: '描述',
                },
                rows: authors.map(author => ({
                    id: author.id,
                    name: author.name,
                    dynasty: author.dynasty,
                    desc: author.desc,
                })),
                adapters: {
                    desc: (desc) => {
                        if (!desc) return desc;
                        return desc.length > 30 ? desc.slice(0, 30) + '...' : desc;
                    },
                },
                operations: [
                    {
                        buttonName: '查看',
                        onClick: (row) => navigate(`/author/${row.id}`),
                        variant: 'info',
                    },
                    {
                        buttonName: '修改',
                        onClick: (row) => {
                            console.log('EditAuthor', row);
                            showEditBox(editBoxArgs.schema, editBoxArgs.options, {
                                id: row.id,
                                name: row.name,
                                dynasty: row.dynasty,
                                desc: row.desc,
                            });
                        },
                        variant: 'warning',
                    },
                    {
                        buttonName: '删除',
                        onClick: (row) => {
                            console.log('DeleteAuthor', row);
                            showMessageBox('删除作者', '确定删除这个作者吗？', 'yesno').then((res) => {
                                if (res !== 'yes')
                                    return;
                                api.deleteAuthorById({ id: row.id }, (err, data, _) => {
                                    if (err) throw err;
                                    console.log(data);
                                    if (data.code === 403)
                                        showMessageBox('删除失败', '权限不足。', 'ok');
                                    else if (data.code !== 0)
                                        showMessageBox('删除失败', data.msg, 'ok');
                                    else {
                                        showMessageBox('删除成功', '删除成功！', 'ok').then(fetchData);
                                    }
                                });
                            });
                        },
                        variant: 'danger',
                    },
                ],
                pagination: {
                    currentPage: currentPage,
                    totalPage: totalPages,
                    gotoPageCallback: gotoPage,
                }
            }} />
        </Container>
    );
}

export default AdminAuthorsPage;